<template>
  <div class="batch-detail">
    <!-- 标签页样式的返回按钮 -->
    <div class="tab-header">
      <div class="tab-item">
        <span>溯源详情</span>
        <el-icon class="close-icon" @click="goBack"><Close /></el-icon>
      </div>
    </div>

    <!-- 产品基本信息和检验报告 -->
    <div class="product-info">
      <div class="product-image">
        <el-image :src="basicInfo.productImage" fit="cover" />
      </div>
      <div class="product-details">
        <div class="details-header">
          <h1 class="product-name">{{ basicInfo.productName }}</h1>
          <div class="operation-buttons">
            <el-button type="info" @click="handleExportQRCode"
              >导出溯源码</el-button
            >
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <span class="label">生产批次：</span>
            <span class="value">{{ basicInfo.batchNumber }}</span>
          </div>
          <div class="info-item">
            <span class="label">保质期：</span>
            <span class="value">{{ basicInfo.shelfLife }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <span class="label">生产许可证号：</span>
            <span class="value">{{ basicInfo.licenseNumber }}</span>
          </div>
          <div class="info-item">
            <span class="label">生产企业：</span>
            <span class="value">{{ basicInfo.manufacturer }}</span>
          </div>
        </div>
        <div class="report-section">
          <h3>产品检验报告</h3>
          <ImageUploader
            :type="1"
            label="检验报告"
            :production-batch="String(route.query.production_Batch || '')"
            class="standard-uploader"
          />
        </div>
      </div>
    </div>

    <!-- 信息标签页 -->
    <div class="nav-buttons">
      <div
        class="nav-button"
        :class="{ active: activeSection === 'breeding' }"
        @click="activeSection = 'breeding'"
      >
        <span class="button-text">养殖信息</span>
        <span class="progress-tag">({{ breedingProgress }})</span>
      </div>
      <div
        class="nav-button"
        :class="{ active: activeSection === 'slaughter' }"
        @click="activeSection = 'slaughter'"
      >
        <span class="button-text">屠宰信息</span>
        <span class="progress-tag">({{ slaughterProgress }})</span>
      </div>
      <div
        class="nav-button"
        :class="{ active: activeSection === 'processing' }"
        @click="activeSection = 'processing'"
      >
        <span class="button-text">深加工信息</span>
        <span class="progress-tag">({{ processingProgress }})</span>
      </div>
    </div>

    <!-- 养殖信息内容 -->
    <div v-if="activeSection === 'breeding'" class="section-content">
      <div class="info-section">
        <div class="section-title">
          <span class="title">养殖信息</span>
          <el-button
            type="primary"
            link
            class="setting-btn"
            @click="breedingDialogVisible = true"
          >
            设置
          </el-button>
        </div>

        <div class="info-row">
          <div class="info-item">
            <span class="label">品种：</span>
            <span class="value">{{ breedingInfo.breed_Type }}</span>
          </div>
          <div class="info-item">
            <span class="label">来源：</span>
            <span class="value">{{ breedingInfo.source_Origin }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <span class="label">饲养天数：</span>
            <span class="value">{{
              breedingInfo.feeding_Days ? breedingInfo.feeding_Days + "天" : ""
            }}</span>
          </div>
          <div class="info-item">
            <span class="label">饲料品牌：</span>
            <span class="value">{{ breedingInfo.feed_Brand }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <span class="label">饲养负责人：</span>
            <span class="value">{{ breedingInfo.breeding_Supervisor }}</span>
          </div>
          <div class="info-item">
            <span class="label">出栏日期：</span>
            <span class="value">{{
              breedingInfo.release_Date
                ? breedingInfo.release_Date.split("T")[0]
                : ""
            }}</span>
          </div>
        </div>

        <!-- 养殖信息设置弹出框 -->
        <el-dialog
          v-model="breedingDialogVisible"
          title="养殖信息"
          width="500px"
          :close-on-click-modal="false"
        >
          <el-form
            ref="breedingFormRef"
            :model="breedingForm"
            :rules="breedingRules"
            label-width="100px"
          >
            <el-form-item label="品种" prop="breed_Type" required>
              <el-input
                v-model="breedingForm.breed_Type"
                placeholder="请输入品种"
              />
            </el-form-item>
            <el-form-item label="来源" prop="source_Origin" required>
              <el-input
                v-model="breedingForm.source_Origin"
                placeholder="请输入来源"
              />
            </el-form-item>
            <el-form-item label="饲养天数" prop="feeding_Days" required>
              <el-input
                v-model="breedingForm.feeding_Days"
                placeholder="请输入饲养天数"
              />
            </el-form-item>
            <el-form-item label="饲料品牌" prop="feed_Brand" required>
              <el-input
                v-model="breedingForm.feed_Brand"
                placeholder="请输入饲料品牌"
              />
            </el-form-item>
            <el-form-item
              label="饲养负责人"
              prop="breeding_Supervisor"
              required
            >
              <el-input
                v-model="breedingForm.breeding_Supervisor"
                placeholder="请输入饲养负责人"
              />
            </el-form-item>
            <el-form-item label="出栏日期" prop="release_Date" required>
              <el-date-picker
                v-model="breedingForm.release_Date"
                type="date"
                placeholder="请选择出栏日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="breedingDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSaveBreedingInfo"
                >保存</el-button
              >
            </span>
          </template>
        </el-dialog>
      </div>

      <div class="health-section">
        <div class="section-title">
          <span class="title">免疫信息</span>
          <div class="button-group">
            <el-button
              type="primary"
              link
              class="add-btn"
              @click="handleAddHealthRecord"
            >
              新增行
            </el-button>
          </div>
        </div>

        <div class="health-table">
          <el-table :data="healthRecords" border>
            <template #empty>
              <el-empty description="暂无免疫信息" />
            </template>
            <el-table-column
              prop="feeding_Days"
              label="饲养天数"
              min-width="100"
            >
              <template #default="scope">
                <template v-if="scope.row.isEditing">
                  <el-input
                    v-model="scope.row.feeding_Days"
                    placeholder="请输入饲养天数"
                    maxlength="5"
                    :show-word-limit="true"
                    @input="validateFeedingDays($event, scope.row)"
                  />
                </template>
                <template v-else> {{ scope.row.feeding_Days }}天 </template>
              </template>
            </el-table-column>
            <el-table-column
              prop="immune_System"
              label="免疫方式"
              min-width="120"
            >
              <template #default="scope">
                <template v-if="scope.row.isEditing">
                  <el-input
                    v-model="scope.row.immune_System"
                    placeholder="请输入免疫方式"
                    maxlength="30"
                    :show-word-limit="true"
                    @input="
                      (value: string) =>
                        validateImmuneInput(value, 'immune_System', scope.row)
                    "
                  />
                </template>
                <template v-else>
                  {{ scope.row.immune_System }}
                </template>
              </template>
            </el-table-column>
            <el-table-column
              prop="immune_Methods"
              label="免疫方法"
              min-width="120"
            >
              <template #default="scope">
                <template v-if="scope.row.isEditing">
                  <el-input
                    v-model="scope.row.immune_Methods"
                    placeholder="请输入免疫方法"
                    maxlength="30"
                    :show-word-limit="true"
                    @input="
                      (value: string) =>
                        validateImmuneInput(value, 'immune_Methods', scope.row)
                    "
                  />
                </template>
                <template v-else>
                  {{ scope.row.immune_Methods }}
                </template>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <div class="operation-buttons">
                  <template v-if="scope.row.isEditing">
                    <el-button
                      type="primary"
                      link
                      size="small"
                      @click="handleSaveRow(scope.$index)"
                      >保存</el-button
                    >
                    <el-button
                      type="info"
                      link
                      size="small"
                      @click="handleCancelEdit(scope.$index)"
                      >取消</el-button
                    >
                  </template>
                  <template v-else>
                    <el-button
                      type="primary"
                      link
                      size="small"
                      @click="handleEditRow(scope.$index)"
                      >修改</el-button
                    >
                    <el-button
                      type="danger"
                      link
                      size="small"
                      @click="handleDeleteHealthRecord(scope.row.id)"
                      >删除</el-button
                    >
                  </template>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="section-block">
        <div class="section-title">
          <span class="title">动检证</span>
        </div>
        <ImageUploader
          :type="2"
          label="动检证"
          :production-batch="String(route.query.production_Batch || '')"
          class="standard-uploader"
          @change="(newImages) => (animalCertImages = newImages)"
        />
      </div>

      <div class="enterprise-section">
        <div class="section-block">
          <div class="section-title">
            <span class="title">企业信息</span>
            <el-button
              type="primary"
              link
              class="setting-btn"
              @click="enterpriseDialogVisible = true"
            >
              设置
            </el-button>
          </div>
          <div class="enterprise-info-grid">
            <div class="info-item">
              <span class="label">养殖场：</span>
              <span class="value">{{ enterpriseInfo.livestock_Farm }}</span>
            </div>
            <div class="info-item">
              <span class="label">负责人：</span>
              <span class="value">{{ enterpriseInfo.farm_Manager }}</span>
            </div>
            <div class="info-item">
              <span class="label">存栏数量：</span>
              <span class="value">{{
                enterpriseInfo.inventory_Quantity
                  ? enterpriseInfo.inventory_Quantity + "只"
                  : ""
              }}</span>
            </div>
          </div>

          <!-- 企业信息设置弹出框 -->
          <el-dialog
            v-model="enterpriseDialogVisible"
            title="企业信息"
            width="500px"
            :close-on-click-modal="false"
          >
            <el-form
              ref="enterpriseFormRef"
              :model="enterpriseForm"
              :rules="enterpriseRules"
              label-width="100px"
            >
              <el-form-item label="养殖场" prop="livestock_Farm" required>
                <el-input
                  v-model="enterpriseForm.livestock_Farm"
                  placeholder="请输入养殖场名称"
                />
              </el-form-item>
              <el-form-item label="负责人" prop="farm_Manager" required>
                <el-input
                  v-model="enterpriseForm.farm_Manager"
                  placeholder="请输入负责人姓名"
                />
              </el-form-item>
              <el-form-item label="存栏数量" prop="inventory_Quantity" required>
                <el-input
                  v-model="enterpriseForm.inventory_Quantity"
                  placeholder="请输入存栏数量"
                >
                  <template #append>只</template>
                </el-input>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="enterpriseDialogVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" @click="handleSaveEnterpriseInfo"
                  >保存</el-button
                >
              </span>
            </template>
          </el-dialog>
        </div>

        <div class="section-block">
          <div class="section-title">
            <span class="title">企业照片</span>
          </div>
          <ImageUploader
            :type="3"
            label="企业照片"
            :production-batch="String(route.query.production_Batch || '')"
            class="standard-uploader"
            @change="(newImages) => (breedingCompanyImages = newImages)"
          />
        </div>
      </div>
    </div>

    <!-- 屠宰信息内容 -->
    <div v-if="activeSection === 'slaughter'" class="section-content">
      <div class="info-section">
        <div class="section-title">
          <span class="title">屠宰信息</span>
          <el-button
            type="primary"
            link
            class="setting-btn"
            @click="slaughterDialogVisible = true"
          >
            设置
          </el-button>
        </div>

        <div class="info-row">
          <div class="info-item">
            <span class="label">批次：</span>
            <span class="value">{{ slaughterInfo.batch_No }}</span>
          </div>
          <div class="info-item">
            <span class="label">到厂均重：</span>
            <span class="value">{{
              slaughterInfo.average_Weight
                ? slaughterInfo.average_Weight + "公斤"
                : ""
            }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <span class="label">到厂时间：</span>
            <span class="value">{{
              formatDateTime(slaughterInfo.arrival_Time)
            }}</span>
          </div>
          <div class="info-item">
            <span class="label">屠宰时间：</span>
            <span class="value">{{
              formatDateTime(slaughterInfo.slaughter_Time)
            }}</span>
          </div>
        </div>

        <!-- 屠宰信息设置弹出框 -->
        <el-dialog
          v-model="slaughterDialogVisible"
          title="屠宰信息"
          width="500px"
          :close-on-click-modal="false"
        >
          <el-form
            ref="slaughterFormRef"
            :model="slaughterForm"
            :rules="slaughterRules"
            label-width="100px"
          >
            <el-form-item label="批次" prop="batch_No" required>
              <el-input
                v-model="slaughterForm.batch_No"
                placeholder="请输入批次号"
                maxlength="30"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="到厂均重" prop="average_Weight" required>
              <el-input
                v-model="slaughterForm.average_Weight"
                placeholder="请输入到厂均重"
                maxlength="5"
                show-word-limit
              >
                <template #append>公斤</template>
              </el-input>
            </el-form-item>
            <el-form-item label="到厂时间" prop="arrival_Time" required>
              <el-date-picker
                v-model="slaughterForm.arrival_Time"
                type="datetime"
                placeholder="请选择到厂时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
                :default-time="new Date(2000, 1, 1, 0, 0, 0)"
                style="width: 100%"
                clearable
                :editable="false"
              />
            </el-form-item>
            <el-form-item label="屠宰时间" prop="slaughter_Time" required>
              <el-date-picker
                v-model="slaughterForm.slaughter_Time"
                type="datetime"
                placeholder="请选择屠宰时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
                :default-time="new Date(2000, 1, 1, 0, 0, 0)"
                style="width: 100%"
                clearable
                :editable="false"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="slaughterDialogVisible = false"
                >取消</el-button
              >
              <el-button type="primary" @click="handleSaveSlaughterInfo"
                >保存</el-button
              >
            </span>
          </template>
        </el-dialog>
      </div>

      <div class="section-block">
        <div class="section-title">
          <span class="title">相关资质</span>
        </div>
        <ImageUploader
          :type="4"
          label="相关资质"
          :production-batch="String(route.query.production_Batch || '')"
          class="standard-uploader"
          @change="(newImages) => (slaughterImages = newImages)"
        />
      </div>

      <div class="enterprise-section">
        <div class="info-section">
          <div class="section-title">
            <span class="title">企业信息</span>
            <el-button
              type="primary"
              link
              class="setting-btn"
              @click="enterpriseDialogVisible = true"
            >
              设置
            </el-button>
          </div>

          <div class="info-row">
            <div class="info-item">
              <span class="label">公司名称：</span>
              <span class="value">{{ enterpriseInfo.corporate_Name }}</span>
            </div>
            <div class="info-item">
              <span class="label">公司地址：</span>
              <span class="value">{{
                enterpriseInfo.province
                  ? enterpriseInfo.province +
                    (enterpriseInfo.location_City
                      ? " " + enterpriseInfo.location_City
                      : "") +
                    (enterpriseInfo.detailed_Address
                      ? " " + enterpriseInfo.detailed_Address
                      : "")
                  : ""
              }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="label">成立时间：</span>
              <span class="value">{{
                enterpriseInfo.establishment_Date
                  ? convertISOToChineseDate(enterpriseInfo.establishment_Date)
                  : ""
              }}</span>
            </div>
            <div class="info-item">
              <span class="label">公司简介：</span>
              <span class="value">{{ enterpriseInfo.company_Profile }}</span>
            </div>
          </div>

          <!-- 企业信息设置弹出框 -->
          <el-dialog
            v-model="enterpriseDialogVisible"
            title="企业信息"
            width="500px"
            :close-on-click-modal="false"
          >
            <el-form
              ref="enterpriseFormRef"
              :model="enterpriseForm"
              :rules="enterpriseRules"
              label-width="100px"
            >
              <el-form-item label="公司名称" prop="corporate_Name" required>
                <el-input
                  v-model="enterpriseForm.corporate_Name"
                  placeholder="请输入公司名称"
                  maxlength="30"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item label="公司地址" required>
                <div class="address-inputs">
                  <el-form-item prop="province" class="address-select-item">
                    <el-select
                      v-model="enterpriseForm.province"
                      placeholder="请选择省份"
                      class="address-select"
                      @change="handleProvinceChange"
                    >
                      <el-option
                        v-for="item in provinceList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    prop="location_City"
                    class="address-select-item"
                  >
                    <el-select
                      v-model="enterpriseForm.location_City"
                      placeholder="请选择城市"
                      class="address-select"
                    >
                      <el-option
                        v-for="item in cityList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    prop="detailed_Address"
                    class="address-input-item"
                  >
                    <el-input
                      v-model="enterpriseForm.detailed_Address"
                      placeholder="请输入详细地址"
                      class="address-input"
                      maxlength="100"
                      show-word-limit
                    />
                  </el-form-item>
                </div>
              </el-form-item>
              <el-form-item label="成立时间" prop="establishment_Date" required>
                <el-date-picker
                  v-model="enterpriseForm.establishment_Date"
                  type="date"
                  placeholder="请选择成立时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="公司简介" prop="company_Profile">
                <el-input
                  v-model="enterpriseForm.company_Profile"
                  type="textarea"
                  :rows="3"
                  placeholder="选填，请输入公司简介"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="enterpriseDialogVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" @click="handleSaveEnterpriseInfo"
                  >保存</el-button
                >
              </span>
            </template>
          </el-dialog>
        </div>

        <div class="section-block">
          <div class="section-title">
            <span class="title">企业照片</span>
          </div>
          <ImageUploader
            :type="5"
            label="企业照片"
            :production-batch="String(route.query.production_Batch || '')"
            class="standard-uploader"
            @change="(newImages) => (slaughterCompanyImages = newImages)"
          />
        </div>
      </div>
    </div>

    <!-- 深加工信息内容 -->
    <div v-if="activeSection === 'processing'" class="section-content">
      <div class="info-section">
        <div class="section-title">
          <span class="title">深加工信息</span>
          <el-button
            type="primary"
            link
            class="setting-btn"
            @click="processingDialogVisible = true"
          >
            设置
          </el-button>
        </div>

        <div class="info-row">
          <div class="info-item">
            <span class="label">班组：</span>
            <span class="value">{{ processingInfo.work_Team }}</span>
          </div>
          <div class="info-item">
            <span class="label">负责人：</span>
            <span class="value">{{ processingInfo.responsible_Person }}</span>
          </div>
        </div>

        <!-- 深加工信息设置弹出框 -->
        <el-dialog
          v-model="processingDialogVisible"
          title="深加工信息"
          width="500px"
          :close-on-click-modal="false"
        >
          <el-form
            ref="processingFormRef"
            :model="processingForm"
            :rules="processingRules"
            label-width="100px"
          >
            <el-form-item label="班组" prop="work_Team" required>
              <el-input
                v-model="processingForm.work_Team"
                placeholder="请输入班组"
                maxlength="30"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="负责人" prop="responsible_Person" required>
              <el-input
                v-model="processingForm.responsible_Person"
                placeholder="请输入负责人"
                maxlength="30"
                show-word-limit
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="processingDialogVisible = false"
                >取消</el-button
              >
              <el-button type="primary" @click="handleSaveProcessingInfo"
                >保存</el-button
              >
            </span>
          </template>
        </el-dialog>
      </div>

      <div class="section-block">
        <div class="section-title">
          <span class="title">食品安全信息</span>
        </div>
        <ImageUploader
          :type="6"
          label="食品安全"
          :production-batch="String(route.query.production_Batch || '')"
          class="standard-uploader"
          @change="(newImages) => (safetyImages = newImages)"
        />
      </div>

      <div class="supply-chain-section">
        <div class="section-title">
          <span class="title">供应商信息</span>
        </div>

        <div class="supplier-category">
          <div class="section-title">
            <span class="title">原料</span>
            <el-button
              type="primary"
              link
              class="setting-btn"
              @click="supplierRawDialogVisible = true"
            >
              设置
            </el-button>
          </div>
          <div class="category-info">
            <div class="info-item">
              <span class="label">生产批次：</span>
              <span class="value">{{ supplierInfo[1].batch_Number }}</span>
            </div>
          </div>

          <!-- 原料供应商设置弹出框 -->
          <el-dialog
            v-model="supplierRawDialogVisible"
            title="原料信息"
            width="500px"
            :close-on-click-modal="false"
          >
            <el-form
              ref="supplierRawFormRef"
              :model="supplierForm"
              :rules="supplierRules"
              label-width="100px"
            >
              <el-form-item label="生产批次" prop="batch_Number" required>
                <el-input
                  v-model="supplierForm.batch_Number"
                  placeholder="请输入生产批次"
                  maxlength="30"
                  show-word-limit
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="supplierRawDialogVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" @click="handleSaveSupplierInfo(1)"
                  >保存</el-button
                >
              </span>
            </template>
          </el-dialog>

          <div class="category-title">相关材料</div>
          <ImageUploader
            :type="7"
            label="原料材料"
            :production-batch="String(route.query.production_Batch || '')"
            class="standard-uploader"
          />
        </div>

        <div class="supplier-category">
          <div class="section-title">
            <span class="title">辅料</span>
            <el-button
              type="primary"
              link
              class="setting-btn"
              @click="supplierAuxDialogVisible = true"
            >
              设置
            </el-button>
          </div>
          <div class="category-info">
            <div class="info-item">
              <span class="label">生产批次：</span>
              <span class="value">{{ supplierInfo[2].batch_Number }}</span>
            </div>
          </div>

          <!-- 辅料供应商设置弹出框 -->
          <el-dialog
            v-model="supplierAuxDialogVisible"
            title="辅料信息"
            width="500px"
            :close-on-click-modal="false"
          >
            <el-form
              ref="supplierAuxFormRef"
              :model="supplierForm"
              :rules="supplierRules"
              label-width="100px"
            >
              <el-form-item label="生产批次" prop="batch_Number" required>
                <el-input
                  v-model="supplierForm.batch_Number"
                  placeholder="请输入生产批次"
                  maxlength="30"
                  show-word-limit
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="supplierAuxDialogVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" @click="handleSaveSupplierInfo(2)"
                  >保存</el-button
                >
              </span>
            </template>
          </el-dialog>

          <div class="category-title">相关材料</div>
          <ImageUploader
            :type="8"
            label="辅料材料"
            :production-batch="String(route.query.production_Batch || '')"
            class="standard-uploader"
          />
        </div>

        <div class="supplier-category">
          <div class="section-title">
            <span class="title">添加剂</span>
            <el-button
              type="primary"
              link
              class="setting-btn"
              @click="supplierAddDialogVisible = true"
            >
              设置
            </el-button>
          </div>
          <div class="category-info">
            <div class="info-item">
              <span class="label">生产批次：</span>
              <span class="value">{{ supplierInfo[3].batch_Number }}</span>
            </div>
          </div>

          <!-- 添加剂供应商设置弹出框 -->
          <el-dialog
            v-model="supplierAddDialogVisible"
            title="添加剂信息"
            width="500px"
            :close-on-click-modal="false"
          >
            <el-form
              ref="supplierAddFormRef"
              :model="supplierForm"
              :rules="supplierRules"
              label-width="100px"
            >
              <el-form-item label="生产批次" prop="batch_Number" required>
                <el-input
                  v-model="supplierForm.batch_Number"
                  placeholder="请输入生产批次"
                  maxlength="30"
                  show-word-limit
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="supplierAddDialogVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" @click="handleSaveSupplierInfo(3)"
                  >保存</el-button
                >
              </span>
            </template>
          </el-dialog>

          <div class="category-title">相关材料</div>
          <ImageUploader
            :type="9"
            label="添加剂材料"
            :production-batch="String(route.query.production_Batch || '')"
            class="standard-uploader"
          />
        </div>

        <div class="supplier-category">
          <div class="section-title">
            <span class="title">包材</span>
            <el-button
              type="primary"
              link
              class="setting-btn"
              @click="supplierPackDialogVisible = true"
            >
              设置
            </el-button>
          </div>
          <div class="category-info">
            <div class="info-item">
              <span class="label">生产批次：</span>
              <span class="value">{{ supplierInfo[4].batch_Number }}</span>
            </div>
          </div>

          <!-- 包材供应商设置弹出框 -->
          <el-dialog
            v-model="supplierPackDialogVisible"
            title="包材信息"
            width="500px"
            :close-on-click-modal="false"
          >
            <el-form
              ref="supplierPackFormRef"
              :model="supplierForm"
              :rules="supplierRules"
              label-width="100px"
            >
              <el-form-item label="生产批次" prop="batch_Number" required>
                <el-input
                  v-model="supplierForm.batch_Number"
                  placeholder="请输入生产批次"
                  maxlength="30"
                  show-word-limit
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="supplierPackDialogVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" @click="handleSaveSupplierInfo(4)"
                  >保存</el-button
                >
              </span>
            </template>
          </el-dialog>

          <div class="category-title">相关材料</div>
          <ImageUploader
            :type="10"
            label="包材材料"
            :production-batch="String(route.query.production_Batch || '')"
            class="standard-uploader"
          />
        </div>
      </div>

      <div class="enterprise-section">
        <div class="section-block">
          <div class="section-title">
            <span class="title">企业信息</span>
            <el-button
              type="primary"
              link
              class="setting-btn"
              @click="processingEnterpriseDialogVisible = true"
            >
              设置
            </el-button>
          </div>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">公司名称：</span>
              <span class="value">{{ processingInfo.corporate_Name }}</span>
            </div>
            <div class="info-item">
              <span class="label">生产许可证号：</span>
              <span class="value">{{ processingInfo.production_License }}</span>
            </div>
          </div>

          <!-- 企业信息设置弹出框 -->
          <el-dialog
            v-model="processingEnterpriseDialogVisible"
            title="企业信息"
            width="500px"
            :close-on-click-modal="false"
          >
            <el-form
              ref="processingEnterpriseFormRef"
              :model="processingForm"
              :rules="processingRules"
              label-width="100px"
            >
              <el-form-item label="公司名称" prop="corporate_Name" required>
                <el-input
                  v-model="processingForm.corporate_Name"
                  placeholder="请输入公司名称"
                />
              </el-form-item>
              <el-form-item label="许可证号" prop="production_License" required>
                <el-input
                  v-model="processingForm.production_License"
                  placeholder="请输入生产许可证号"
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="processingEnterpriseDialogVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" @click="handleSaveProcessingInfo"
                  >保存</el-button
                >
              </span>
            </template>
          </el-dialog>
        </div>

        <div class="section-block">
          <div class="section-title">
            <span class="title">企业照片</span>
          </div>
          <ImageUploader
            :type="11"
            label="企业照片"
            :production-batch="String(route.query.production_Batch || '')"
            class="standard-uploader"
            @change="(newImages) => (processingCompanyImages = newImages)"
          />
        </div>
      </div>
    </div>

    <!-- 导出二维码弹窗 -->
    <el-dialog
      title="导出设置"
      v-model="exportDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      @close="handleExportDialogClose"
    >
      <el-form
        ref="exportFormRef"
        :model="exportForm"
        :rules="exportRules"
        label-width="100px"
      >
        <el-form-item label="导出数量" prop="exportCount" required>
          <el-input
            v-model="exportForm.exportCount"
            placeholder="请输入导出数量"
            maxlength="4"
            @input="handleExportCountInput"
          >
            <template #append>张</template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="exportDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="confirmExport">打印</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import axios from "axios";
import { regionData, codeToText } from "element-china-area-data";
import ImageUploader from "@/components/ImageUploader.vue";
import { Close } from "@element-plus/icons-vue";
import QRCode from "qrcode";

const router = useRouter();
const route = useRoute();

// 当前显示的部分(养殖、屠宰、深加工页面跳转)
const activeSection = ref<"breeding" | "slaughter" | "processing">("breeding");

// 监听页面切换
watch(activeSection, async (newSection) => {
  try {
    // 只在数据为空时重新加载
    switch (newSection) {
      case "breeding":
        if (!breedingInfo.value.breed_Type) {
          await Promise.all([getBreedingInfo(), getImmuneList()]);
        }
        break;
      case "slaughter":
        if (!slaughterInfo.value.batch_No) {
          await getSlaughterInfo();
        }
        break;
      case "processing":
        if (
          !processingInfo.value.work_Team ||
          !Object.keys(supplierInfo.value).length
        ) {
          await Promise.all([getProcessingInfo(), getSupplierInfo()]);
        }
        break;
    }
  } catch (error) {
    ElMessage.error("数据加载失败，请刷新页面重试");
  }
});

// 只保留一个onMounted，并优化初始化逻辑
onMounted(async () => {
  try {
    // 首先获取基本信息
    await getBatchDetail();

    // 同时获取所有页面的数据和图片
    await Promise.all([
      // 养殖信息相关数据
      getBreedingInfo(),
      getImmuneList(),
      // 屠宰信息相关数据
      getSlaughterInfo(),
      // 深加工信息相关数据
      getProcessingInfo(),
      getSupplierInfo(),
      // 企业信息（所有页面都需要）
      getEnterpriseInfo(),
    ]);

    // 如果有路由状态数据，更新基本信息
    const state = history.state?.state;
    if (state?.basicInfo) {
      basicInfo.value = state.basicInfo;
    }
  } catch (error) {
    ElMessage.error("数据加载失败，请刷新页面重试");
  }
});

//基本信息相关方法
// 基本信息
const basicInfo = ref({
  productName: "", // 产品名称
  batchNumber: "", // 生产批次
  shelfLife: "", // 保质期
  licenseNumber: "", // 生产许可证号
  manufacturer: "", // 生产企业
  productImage: "", // 产品图片
});

//根据生产批次获取基本信息
const getBatchDetail = () => {
  console.log("路由参数:", route.query.production_Batch);

  axios({
    url: "https://localhost:7008/api/Basic/GetBasic_TraceabilityByProduction_Batch",
    method: "get",
    params: {
      production_Batch: route.query.production_Batch,
    },
  }).then((res) => {
    if (res.data.code === 200) {
      const data = res.data.data;

      basicInfo.value = {
        productName: data.goodsName || "", // 产品名称
        batchNumber: data.production_Batch || "", // 生产批次
        shelfLife: data.quality_Guarantee + "天" || "", // 保质期
        licenseNumber: data.production_License || "", // 生产许可证号
        manufacturer: data.manufacturing_Enterprise || "", // 生产企业
        productImage: data.cover_Image || "", // 产品图片
      };
    } else {
      ElMessage.error(res.data.msg || "获取数据失败");
    }
  });
};

//养殖信息相关方法
// 养殖信息表单接口定义
interface BreedingFormData {
  breed_Type: string;
  source_Origin: string;
  feeding_Days: number;
  feed_Brand: string;
  breeding_Supervisor: string;
  release_Date: string;
  production_Batch: string;
}

const breedingDialogVisible = ref(false);
const breedingFormRef = ref();

const breedingInfo = ref({
  breed_Type: "",
  source_Origin: "",
  feeding_Days: "",
  feed_Brand: "",
  breeding_Supervisor: "",
  release_Date: "",
});

const breedingForm = ref<BreedingFormData>({
  breed_Type: "",
  source_Origin: "",
  feeding_Days: 0,
  feed_Brand: "",
  breeding_Supervisor: "",
  release_Date: "",
  production_Batch: "",
});

// 根据生产批次获取养殖信息的方法
const getBreedingInfo = () => {
  console.log("获取养殖信息，生产批次:", route.query.production_Batch);

  axios({
    url: "https://localhost:7008/api/Breeding/GetBreeding",
    method: "get",
    params: {
      production_Batch: route.query.production_Batch,
    },
  }).then((res) => {
    const data = res.data.data[0];
    // 直接使用API返回的数据结构
    breedingInfo.value = {
      breed_Type: data.breed_Type || "",
      source_Origin: data.source_Origin || "",
      feeding_Days: data.feeding_Days || "",
      feed_Brand: data.feed_Brand || "",
      breeding_Supervisor: data.breeding_Supervisor || "",
      release_Date: data.release_Date || "",
    };
  });
};

// 养殖信息验证规则
const breedingRules = {
  breed_Type: [
    { required: true, message: "请输入品种", trigger: "change" },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
      message: "只允许输入中文、字母",
      trigger: "change",
    },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!value && !breedingInfo.value.breed_Type) {
          callback(new Error("请输入品种"));
        } else if (value && /[,?!@#$%^&*]/.test(value)) {
          callback(new Error("不允许输入特殊字符（如逗号、问号等）"));
        } else if (value && value.length > 30) {
          callback(new Error("最多支持输入30位字符"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  source_Origin: [
    { required: true, message: "请输入来源", trigger: "change" },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
      message: "只允许输入中文、字母",
      trigger: "change",
    },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!value && !breedingInfo.value.source_Origin) {
          callback(new Error("请输入来源"));
        } else if (value && /[,?!@#$%^&*]/.test(value)) {
          callback(new Error("不允许输入特殊字符（如逗号、问号等）"));
        } else if (value && value.length > 30) {
          callback(new Error("最多支持输入30位字符"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  feeding_Days: [
    { required: true, message: "请输入饲养天数", trigger: "change" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!value && !breedingInfo.value.feeding_Days) {
          callback(new Error("请输入饲养天数"));
        } else if (value && !/^\d{1,5}$/.test(value)) {
          callback(new Error("只允许输入数字，最多5位"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  feed_Brand: [
    { required: true, message: "请输入饲料品牌", trigger: "change" },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
      message: "只允许输入中文、字母",
      trigger: "change",
    },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!value && !breedingInfo.value.feed_Brand) {
          callback(new Error("请输入饲料品牌"));
        } else if (value && /[,?!@#$%^&*]/.test(value)) {
          callback(new Error("不允许输入特殊字符（如逗号、问号等）"));
        } else if (value && value.length > 30) {
          callback(new Error("最多支持输入30位字符"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  breeding_Supervisor: [
    { required: true, message: "请输入饲养负责人", trigger: "change" },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
      message: "只允许输入中文、字母",
      trigger: "change",
    },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!value && !breedingInfo.value.breeding_Supervisor) {
          callback(new Error("请输入饲养负责人"));
        } else if (value && /[,?!@#$%^&*]/.test(value)) {
          callback(new Error("不允许输入特殊字符（如逗号、问号等）"));
        } else if (value && value.length > 30) {
          callback(new Error("最多支持输入30位字符"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  release_Date: [
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!value && !breedingInfo.value.release_Date) {
          callback(new Error("请选择出栏日期"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 打开弹窗时初始化养殖信息表单数据
watch(breedingDialogVisible, (val) => {
  if (val) {
    // 将显示的数据转换为养殖信息表单数据格式
    breedingForm.value = {
      breed_Type: breedingInfo.value.breed_Type,
      source_Origin: breedingInfo.value.source_Origin,
      feeding_Days: Number(breedingInfo.value.feeding_Days) || 0,
      feed_Brand: breedingInfo.value.feed_Brand,
      breeding_Supervisor: breedingInfo.value.breeding_Supervisor,
      release_Date: breedingInfo.value.release_Date,
      production_Batch: route.query.production_Batch as string,
    };
    // 清除表单的验证信息
    if (breedingFormRef.value) {
      breedingFormRef.value.clearValidate();
    }
  }
});

// 保存养殖信息
const handleSaveBreedingInfo = async () => {
  if (!breedingFormRef.value) return;

  await breedingFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        axios({
          url: "https://localhost:7008/api/Breeding/CreateBreeding",
          method: "post",
          data: breedingForm.value,
        }).then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.msg);
            breedingDialogVisible.value = false;
            getBreedingInfo();
          } else {
            ElMessage.error(res.data.msg);
          }
        });
      } catch (error) {
        ElMessage.error("保存失败，请检查网络连接");
      }
    }
  });
};

//免疫信息操作相关方法
//根据生产批次获取免疫信息
const getImmuneList = () => {
  axios({
    url: "https://localhost:7008/api/Immune/GetImmune",
    method: "get",
    params: {
      production_Batch: route.query.production_Batch,
    },
  }).then((res) => {
    healthRecords.value = res.data.data;
  });
};

// 在 script setup 开始处添加接口定义
interface HealthRecord {
  id?: number; // 新增id字段，支持后端返回的主键
  feeding_Days: string | number; // 修改类型以支持字符串输入
  immune_System: string;
  immune_Methods: string;
  production_Batch: string;
  isEditing?: boolean;
}

// 修改免疫信息接口定义
interface ImmuneRecord {
  feeding_Days: string | number; // 修改类型以支持字符串输入
  immune_System: string;
  immune_Methods: string;
  production_Batch: string;
  isEditing?: boolean;
}
// 添加验证方法
const validateFeedingDays = (value: string | number, row: ImmuneRecord) => {
  // 确保value是字符串
  const strValue = String(value);
  // 只允许输入数字
  const numericValue = strValue.replace(/[^\d]/g, "");
  // 最多5位数字
  row.feeding_Days = numericValue.slice(0, 5);
};

// 免疫信息数据定义
const healthRecords = ref<HealthRecord[]>([]);

// 免疫信息备份数据定义
const originalHealthRecords = ref<HealthRecord[]>([]);

// 添加新的免疫信息行
const handleAddHealthRecord = () => {
  healthRecords.value.push({
    feeding_Days: "",
    immune_System: "",
    immune_Methods: "",
    production_Batch: route.query.production_Batch as string,
    isEditing: true,
  });
};

// 编辑免疫信息行
const handleEditRow = (index: number) => {
  // 备份当前行数据
  originalHealthRecords.value[index] = { ...healthRecords.value[index] };
  healthRecords.value[index].isEditing = true;
};

// 添加免疫信息验证方法
const validateImmuneInput = (
  value: string,
  type: "immune_System" | "immune_Methods",
  row: any
) => {
  // 检查免疫信息是否为空
  if (!value) {
    return;
  }

  let newValue = value;
  let isModified = false;

  // 检查特殊字符
  if (/[,?!@#$%^&*]/.test(value)) {
    ElMessage.warning(
      `${
        type === "immune_System" ? "免疫方式" : "免疫方法"
      }不能包含特殊字符（如逗号、问号等）`
    );
    newValue = value.replace(/[,?!@#$%^&*]/g, "");
    isModified = true;
  }

  // 检查字符类型
  if (!/^[\u4e00-\u9fa5a-zA-Z]*$/.test(newValue)) {
    ElMessage.warning(
      `${
        type === "immune_System" ? "免疫方式" : "免疫方法"
      }只允许输入中文、字母`
    );
    newValue = newValue.replace(/[^\u4e00-\u9fa5a-zA-Z]/g, "");
    isModified = true;
  }

  // 检查长度
  if (newValue.length > 30) {
    ElMessage.warning(
      `${
        type === "immune_System" ? "免疫方式" : "免疫方法"
      }最多支持输入30位字符`
    );
    newValue = newValue.slice(0, 30);
    isModified = true;
  }

  // 如果有修改，更新值
  if (isModified) {
    row[type] = newValue;
  }

  return !isModified;
};

// 保存单行免疫信息
const handleSaveRow = async (index: number) => {
  const record = healthRecords.value[index];

  // 验证饲养天数
  if (!record.feeding_Days) {
    ElMessage.warning("请填写饲养天数");
    return;
  }
  if (!/^\d{1,5}$/.test(String(record.feeding_Days))) {
    ElMessage.warning("饲养天数必须是1-5位的数字");
    return;
  }

  // 使用validateImmuneInput进行验证
  let isValid = true;
  // 验证免疫方式
  if (!record.immune_System) {
    ElMessage.warning("请填写免疫方式");
    return;
  }
  validateImmuneInput(record.immune_System, "immune_System", record);
  if (record.immune_System !== healthRecords.value[index].immune_System) {
    isValid = false;
  }

  // 验证免疫方法
  if (!record.immune_Methods) {
    ElMessage.warning("请填写免疫方法");
    return;
  }
  validateImmuneInput(record.immune_Methods, "immune_Methods", record);
  if (record.immune_Methods !== healthRecords.value[index].immune_Methods) {
    isValid = false;
  }

  if (!isValid) {
    return;
  }

  try {
    // 判断是新增还是修改免疫信息
    const isEdit = record.id !== undefined && record.id !== null;
    const url = isEdit
      ? "https://localhost:7008/api/Immune/UpdateImmune"
      : "https://localhost:7008/api/Immune/CreateImmune";
    const method = "post";
    const data = isEdit
      ? {
          id: record.id,
          feeding_Days: Number(record.feeding_Days),
          immune_System: record.immune_System,
          immune_Methods: record.immune_Methods,
          production_Batch: route.query.production_Batch,
        }
      : {
          feeding_Days: Number(record.feeding_Days),
          immune_System: record.immune_System,
          immune_Methods: record.immune_Methods,
          production_Batch: route.query.production_Batch,
        };
    const response = await axios({ url, method, data });
    if (response.data.code === 200) {
      record.isEditing = false;
      ElMessage.success(response.data.msg || "保存成功");
      getImmuneList();
    } else {
      ElMessage.error(response.data.msg || "保存失败");
    }
  } catch (error) {
    ElMessage.error("保存失败，请检查网络连接");
  }
};

// 取消编辑免疫信息行
const handleCancelEdit = (index: number) => {
  if (originalHealthRecords.value[index]) {
    // 恢复原有免疫信息数据
    healthRecords.value[index] = {
      ...originalHealthRecords.value[index],
      isEditing: false,
    };
  } else {
    // 新增的免疫信息行，直接删除
    healthRecords.value.splice(index, 1);
  }
};

// 删除免疫信息
const handleDeleteHealthRecord = (id: number) => {
  ElMessageBox.confirm("确认删除该记录吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios({
        url: "https://localhost:7008/api/Immune/DeleteImmune",
        method: "delete",
        params: {
          id: id,
        },
      }).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success(res.data.msg);
          getImmuneList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {});
};

// 屠宰信息相关方法
// 屠宰信息接口定义
interface SlaughterFormData {
  batch_No: string;
  average_Weight: number;
  arrival_Time: string | null;
  slaughter_Time: string | null;
  production_Batch: string;
}

// 屠宰信息数据
const slaughterDialogVisible = ref(false);
const slaughterFormRef = ref();

const slaughterInfo = ref<SlaughterFormData>({
  batch_No: "",
  average_Weight: 0,
  arrival_Time: null,
  slaughter_Time: null,
  production_Batch: "",
});

const slaughterForm = ref<SlaughterFormData>({
  batch_No: "",
  average_Weight: 0,
  arrival_Time: null,
  slaughter_Time: null,
  production_Batch: route.query.production_Batch as string,
});

// 屠宰信息批次号验证规则
const validateBatchNo = (rule: any, value: string, callback: any) => {
  if (!value && !slaughterInfo.value.batch_No) {
    callback(new Error("请输入批次号"));
    return;
  }
  if (value) {
    const specialChars = /[,?!@#$%^&*]/;
    const validChars = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/;
    if (specialChars.test(value)) {
      callback(new Error("不能输入特殊字符"));
    } else if (!validChars.test(value)) {
      callback(new Error("只能输入中文、英文和数字"));
    } else if (value.length > 30) {
      callback(new Error("最多输入30个字符"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};

// 屠宰信息到厂均重验证规则
const validateWeight = (rule: any, value: string, callback: any) => {
  if (!value && !slaughterInfo.value.average_Weight) {
    callback(new Error("请输入到厂均重"));
    return;
  }
  if (value) {
    const numberReg = /^\d{1,5}(\.\d{1,2})?$/;
    if (!numberReg.test(value)) {
      callback(new Error("请输入正确的数字格式，最多5位整数，2位小数"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};

const slaughterRules = {
  batch_No: [
    { required: true, message: "请输入批次号", trigger: "blur" },
    { validator: validateBatchNo, trigger: "blur" },
  ],
  average_Weight: [
    { required: true, message: "请输入到厂均重", trigger: "blur" },
    { validator: validateWeight, trigger: "blur" },
  ],
  arrival_Time: [
    { required: true, message: "请选择到厂时间", trigger: "blur" },
  ],
  slaughter_Time: [
    { required: true, message: "请选择屠宰时间", trigger: "blur" },
  ],
};

// 获取屠宰信息
const getSlaughterInfo = () => {
  axios({
    url: "https://localhost:7008/api/Slaughter/GetSlaughter",
    method: "get",
    params: {
      production_Batch: route.query.production_Batch as string,
    },
  }).then((res) => {
    const data = res.data.data[0];

    // 转换时间格式
    const formattedData = {
      batch_No: data.batch_No || "",
      average_Weight: Number(data.average_Weight || 0),
      arrival_Time: data.arrival_Time
        ? convertToISOString(data.arrival_Time)
        : null,
      slaughter_Time: data.slaughter_Time
        ? convertToISOString(data.slaughter_Time)
        : null,
      production_Batch:
        data.production_Batch || (route.query.production_Batch as string),
    };

    slaughterInfo.value = formattedData;
  });
};

// 保存屠宰信息
const handleSaveSlaughterInfo = async () => {
  if (!slaughterFormRef.value) return;

  await slaughterFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const formData = {
        batch_No: slaughterForm.value.batch_No,
        average_Weight: Number(slaughterForm.value.average_Weight),
        arrival_Time: slaughterForm.value.arrival_Time,
        slaughter_Time: slaughterForm.value.slaughter_Time,
        production_Batch: route.query.production_Batch as string,
      };

      try {
        const res = await axios({
          url: "https://localhost:7008/api/Slaughter/CreateSlaughter",
          method: "post",
          data: formData,
        });

        if (res.data.code === 200) {
          ElMessage.success(res.data.msg);
          slaughterDialogVisible.value = false;
          // 保存成功后立即更新本地数据
          slaughterInfo.value = { ...formData };
          // 然后从服务器刷新数据
          getSlaughterInfo();
        } else {
          ElMessage.error(res.data.msg);
        }
      } catch (error) {
        ElMessage.error("保存失败，请检查网络连接");
      }
    }
  });
};

//深加工信息相关方法
// 在 script setup 中添加相关变量和方法
// 深加工信息接口定义
interface ProcessingInfo {
  work_Team: string;
  responsible_Person: string;
  production_Batch: string;
  corporate_Name: string;
  production_License: string;
}

// 深加工信息数据
const processingDialogVisible = ref(false);
const processingFormRef = ref();

const processingInfo = ref<ProcessingInfo>({
  work_Team: "",
  responsible_Person: "",
  production_Batch: "",
  corporate_Name: "",
  production_License: "",
});

const processingForm = ref<ProcessingInfo>({
  work_Team: "",
  responsible_Person: "",
  production_Batch: route.query.production_Batch as string,
  corporate_Name: "",
  production_License: "",
});

// 添加深加工信息的验证规则
const validateProcessingField = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error("该字段为必填项"));
    return;
  }
  // 检查特殊字符
  const specialChars = /[,?!@#$%^&*]/;
  if (specialChars.test(value)) {
    callback(new Error("不能输入特殊字符"));
    return;
  }
  // 检查字符长度
  if (value.length > 30) {
    callback(new Error("最多输入30个字符"));
    return;
  }
  // 检查允许的字符（中文、英文字母）
  const validChars = /^[\u4e00-\u9fa5a-zA-Z\s]+$/;
  if (!validChars.test(value)) {
    callback(new Error("只能输入中文和英文字母"));
    return;
  }
  callback();
};

// 添加生产许可证号的验证规则
const validateLicenseNo = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error("该字段为必填项"));
    return;
  }
  // 检查字符长度
  if (value.length > 30) {
    callback(new Error("最多输入30个字符"));
    return;
  }
  // 只允许输入数字和字母（大小写）
  const validChars = /^[a-zA-Z0-9]+$/;
  if (!validChars.test(value)) {
    callback(new Error("只能输入数字和字母"));
    return;
  }
  callback();
};

const processingRules = {
  corporate_Name: [
    { required: true, message: "请输入公司名称", trigger: "blur" },
    { validator: validateProcessingField, trigger: "blur" },
  ],
  production_License: [
    { required: true, message: "请输入生产许可证号", trigger: "blur" },
    { validator: validateLicenseNo, trigger: "blur" },
  ],
  work_Team: [
    { required: true, message: "请输入班组", trigger: "blur" },
    { validator: validateProcessingField, trigger: "blur" },
  ],
  responsible_Person: [
    { required: true, message: "请输入负责人", trigger: "blur" },
    { validator: validateProcessingField, trigger: "blur" },
  ],
};

const processingEnterpriseDialogVisible = ref(false);
const processingEnterpriseFormRef = ref();

// 监听深加工企业信息对话框打开，初始化表单数据
watch(processingEnterpriseDialogVisible, (val) => {
  if (val) {
    processingForm.value = { ...processingInfo.value };
    // 清除表单的验证信息
    if (processingEnterpriseFormRef.value) {
      processingEnterpriseFormRef.value.clearValidate();
    }
  }
});

// 深加工信息打开弹窗时初始化表单数据
watch(processingDialogVisible, (val) => {
  if (val) {
    processingForm.value = { ...processingInfo.value };
    // 清除表单的验证信息
    if (processingFormRef.value) {
      processingFormRef.value.clearValidate();
    }
  }
});

// 保存深加工信息
const handleSaveProcessingInfo = async () => {
  // 根据当前打开的对话框选择要验证的表单
  const formRef = processingDialogVisible.value
    ? processingFormRef.value
    : processingEnterpriseFormRef.value;

  if (!formRef) return;

  await formRef.validate(async (valid: boolean) => {
    if (valid) {
      processingForm.value.production_Batch = route.query
        .production_Batch as string;
      axios({
        url: "https://localhost:7008/api/Processing/CreateProcessing",
        method: "post",
        data: processingForm.value,
      }).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success(res.data.msg);
          processingDialogVisible.value = false;
          processingEnterpriseDialogVisible.value = false;
          // 更新本地数据
          processingInfo.value = { ...processingForm.value };
          // 从服务器刷新数据
          getProcessingInfo();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    }
  });
};

// 根据生产批次获取深加工信息
const getProcessingInfo = () => {
  return new Promise((resolve, reject) => {
    axios({
      url: "https://localhost:7008/api/Processing/GetProcessing",
      method: "get",
      params: {
        production_Batch: route.query.production_Batch,
      },
    }).then((res) => {
      if (res.data.code === 200 && res.data.data.length > 0) {
        processingInfo.value = res.data.data[0];
      } else {
        processingInfo.value = {
          work_Team: "",
          responsible_Person: "",
          production_Batch: route.query.production_Batch as string,
          corporate_Name: "",
          production_License: "",
        };
      }
      resolve(res);
    });
  });
};

const animalCertImages = ref<{ url: string; label: string }[]>([]);
const breedingCompanyImages = ref<{ url: string; label: string }[]>([]);
const slaughterCompanyImages = ref<{ url: string; label: string }[]>([]);
const processingCompanyImages = ref<{ url: string; label: string }[]>([]);
const safetyImages = ref<{ url: string; label: string }[]>([]);
const slaughterImages = ref<{ url: string; label: string }[]>([]);

// 返回上一页
const goBack = () => {
  router.back();
};

// 处理导出溯码
const handleExportQRCode = () => {
  exportDialogVisible.value = true;
};

// 屠宰信息日期格式化函数
const formatDateTime = (dateTimeStr: string | null) => {
  if (!dateTimeStr) return "";
  try {
    const date = new Date(dateTimeStr);
    if (isNaN(date.getTime())) return "";

    // 日期部分转换为中文格式
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const chineseDate = `${year}年${month}月${day}日`;

    // 时间部分保持原格式
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");
    const time = `${hours}:${minutes}:${seconds}`;

    // 组合日期和时间
    return `${chineseDate} ${time}`;
  } catch (error) {
    console.error("日期格式化错误:", error);
    return "";
  }
};

// 屠宰信息ISO格式转换函数
const convertToISOString = (dateTimeStr: string | null) => {
  if (!dateTimeStr) return null;
  try {
    const date = new Date(dateTimeStr);
    if (isNaN(date.getTime())) return null;
    return date.toISOString();
  } catch (error) {
    console.error("ISO日期转换错误:", error);
    return null;
  }
};

// 屠宰信息监听屠宰信息对话框显示状态
watch(slaughterDialogVisible, (val) => {
  if (val) {
    // 确保屠宰信息时间数据正确初始化
    const initialFormData = {
      batch_No: slaughterInfo.value.batch_No || "",
      average_Weight: Number(slaughterInfo.value.average_Weight || 0),
      arrival_Time: convertToISOString(slaughterInfo.value.arrival_Time),
      slaughter_Time: convertToISOString(slaughterInfo.value.slaughter_Time),
      production_Batch: route.query.production_Batch as string,
    };

    slaughterForm.value = initialFormData;
    // 清除屠宰信息表单的验证信息
    if (slaughterFormRef.value) {
      slaughterFormRef.value.clearValidate();
    }
  }
});

// 供应商信息相关方法
// 原料供应商信息相关方法
const supplierRawDialogVisible = ref(false);
const supplierRawFormRef = ref();
const supplierRawInfo = ref({
  batchNo: "",
});
const supplierRawForm = ref({
  batchNo: "",
});

// 辅料供应商信息相关方法
const supplierAuxDialogVisible = ref(false);
const supplierAuxFormRef = ref();
const supplierAuxInfo = ref({
  batchNo: "",
});
const supplierAuxForm = ref({
  batchNo: "",
});

// 添加剂供应商信息相关方法
const supplierAddDialogVisible = ref(false);
const supplierAddFormRef = ref();
const supplierAddInfo = ref({
  batchNo: "",
});
const supplierAddForm = ref({
  batchNo: "",
});

// 包材供应商信息相关方法
const supplierPackDialogVisible = ref(false);
const supplierPackFormRef = ref();
const supplierPackInfo = ref({
  batchNo: "",
});
const supplierPackForm = ref({
  batchNo: "",
});

// 监听供应商信息对话框打开，初始化供应商信息表单数据
watch(supplierRawDialogVisible, (val) => {
  if (val) {
    supplierRawForm.value = { ...supplierRawInfo.value };
    if (supplierRawFormRef.value) {
      supplierRawFormRef.value.clearValidate();
    }
  }
});

watch(supplierAuxDialogVisible, (val) => {
  if (val) {
    supplierAuxForm.value = { ...supplierAuxInfo.value };
    if (supplierAuxFormRef.value) {
      supplierAuxFormRef.value.clearValidate();
    }
  }
});

watch(supplierAddDialogVisible, (val) => {
  if (val) {
    supplierAddForm.value = { ...supplierAddInfo.value };
    if (supplierAddFormRef.value) {
      supplierAddFormRef.value.clearValidate();
    }
  }
});

watch(supplierPackDialogVisible, (val) => {
  if (val) {
    supplierPackForm.value = { ...supplierPackInfo.value };
    if (supplierPackFormRef.value) {
      supplierPackFormRef.value.clearValidate();
    }
  }
});

//企业信息相关方法
// 企业信息接口定义
interface EnterpriseInfo {
  livestock_Farm: string;
  farm_Manager: string;
  inventory_Quantity: number;
  corporate_Name: string;
  province: string;
  location_City: string;
  detailed_Address: string;
  establishment_Date: string;
  company_Profile: string;
  production_Batch: any;
}

const enterpriseInfo: any = ref<EnterpriseInfo>({
  livestock_Farm: "",
  farm_Manager: "",
  inventory_Quantity: 0,
  corporate_Name: "",
  province: "",
  location_City: "",
  detailed_Address: "",
  establishment_Date: "",
  company_Profile: "",
  production_Batch: route.query.production_Batch,
});

const enterpriseForm: any = ref<EnterpriseInfo>({
  livestock_Farm: "",
  farm_Manager: "",
  inventory_Quantity: 0,
  corporate_Name: "",
  province: "",
  location_City: "",
  detailed_Address: "",
  establishment_Date: "",
  company_Profile: "",
  production_Batch: route.query.production_Batch,
});

const validateProfile = (rule: any, value: string, callback: any) => {
  if (value) {
    if (value.length > 500) {
      callback(new Error("公司简介不能超过500个字符"));
    } else if (
      /[,?!@#$%^&*～·！@#￥%……&*（）——+=【】、{}|；：""''《》，。？、]/.test(
        value
      )
    ) {
      callback(new Error("公司简介不能包含特殊字符"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};

const validateAddress = (rule: any, value: string, callback: any) => {
  if (!value && !enterpriseInfo.value.detailed_Address) {
    callback(new Error("请输入详细地址"));
  } else if (value) {
    if (value.length > 100) {
      callback(new Error("详细地址不能超过100个字符"));
    } else if (
      /[,?!@#$%^&*～·！@#￥%……&*（）——+=【】、{}|；：""''《》，。？、]/.test(
        value
      )
    ) {
      callback(new Error("详细地址不能包含特殊字符"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};

// 养殖信息和屠宰信息企业字段输入校验
function validateEnterpriseField(rule: any, value: string, callback: any) {
  if (!value) {
    callback(new Error("该字段不能为空"));
    return;
  }
  if (
    /[,?!@#$%^&*～·！@#￥%……&*（）——+=【】、{}|；：""''《》，。？、]/.test(
      value
    )
  ) {
    callback(new Error("不允许输入特殊字符"));
    return;
  }
  if (value.length > 30) {
    callback(new Error("最多支持输入30位字符"));
    return;
  }
  callback();
}

function validateInventoryQuantity(rule: any, value: string, callback: any) {
  if (!value) {
    callback(new Error("存栏数量不能为空"));
    return;
  }
  if (!/^\d{1,5}$/.test(value)) {
    callback(new Error("只能输入数字，且最多5位"));
    return;
  }
  callback();
}

// 企业信息字段校验规则
const enterpriseRules = {
  livestock_Farm: [
    { required: true, message: "请输入养殖场名称", trigger: "blur" },
    { validator: validateEnterpriseField, trigger: "blur" },
  ],
  farm_Manager: [
    { required: true, message: "请输入负责人姓名", trigger: "blur" },
    { validator: validateEnterpriseField, trigger: "blur" },
  ],
  inventory_Quantity: [
    { required: true, message: "请输入存栏数量", trigger: "blur" },
    { validator: validateInventoryQuantity, trigger: "blur" },
  ],
  corporate_Name: [
    { required: true, message: "请输入公司名称", trigger: "blur" },
    { validator: validateEnterpriseField, trigger: "blur" },
  ],
  company_Profile: [{ validator: validateProfile, trigger: "blur" }],
  province: [{ required: true, message: "请选择省份", trigger: "change" }],
  location_City: [{ required: true, message: "请选择城市", trigger: "change" }],
  detailed_Address: [
    { required: true, message: "请输入详细地址", trigger: "blur" },
    { validator: validateAddress, trigger: "blur" },
  ],
  establishment_Date: [
    { required: true, message: "请选择成立时间", trigger: "blur" },
  ],
};

// 获取省份代码
const getProvinceCode = (provinceName: string) => {
  const province = regionData.find(
    (item) => codeToText[item.value] === provinceName
  );
  return province ? province.value : "";
};

// 获取城市代码
const getCityCode = (provinceCode: string, cityName: string) => {
  const province = regionData.find((item) => item.value === provinceCode);
  if (province && province.children) {
    const city = province.children.find(
      (item) => codeToText[item.value] === cityName
    );
    return city ? city.value : "";
  }
  return "";
};

// 省份和城市数据
const provinceList = regionData;
const cityList = ref<any[]>([]);

// 监听省份变化
const handleProvinceChange = (provinceCode: string) => {
  enterpriseForm.value.location_City = "";

  const province = regionData.find((item) => item.value === provinceCode);
  if (province && province.children) {
    cityList.value = province.children;
  } else {
    cityList.value = [];
  }
};

// 地址编码转名称的工具函数
const getProvinceName = (code: string) => codeToText[code] || "--";
const getCityName = (code: string) => codeToText[code] || "--";

// 企业信息数据
const enterpriseDialogVisible = ref(false);
const enterpriseFormRef = ref();

// 打开弹窗时初始化企业表单数据
watch(enterpriseDialogVisible, (val) => {
  if (val) {
    // 获取省份代码
    const provinceCode = getProvinceCode(enterpriseInfo.value.province);

    // 更新城市列表
    if (provinceCode) {
      const province = regionData.find((item) => item.value === provinceCode);
      if (province && province.children) {
        cityList.value = province.children;
      }
    }

    // 获取城市代码
    const cityCode = getCityCode(
      provinceCode,
      enterpriseInfo.value.location_City
    );

    enterpriseForm.value = {
      ...enterpriseInfo.value,
      province: provinceCode,
      location_City: cityCode,
      production_Batch: route.query.production_Batch,
    };

    // 清除表单的验证信息
    if (enterpriseFormRef.value) {
      enterpriseFormRef.value.clearValidate();
    }
  }
});

// 保存企业信息
const handleSaveEnterpriseInfo = () => {
  if (!enterpriseFormRef.value) return;

  enterpriseFormRef.value.validate((valid: boolean) => {
    if (valid) {
      // 转换省份和城市代码为文字
      const formData = {
        ...enterpriseForm.value,
        province: getProvinceName(enterpriseForm.value.province),
        location_City: getCityName(enterpriseForm.value.location_City),
      };

      axios({
        url: "https://localhost:7008/api/Company/CreateCompany",
        method: "post",
        data: formData,
      }).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success(res.data.msg);
          enterpriseDialogVisible.value = false;
          getEnterpriseInfo();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    }
  });
};

// 获取企业信息
const getEnterpriseInfo = () => {
  axios({
    url: "https://localhost:7008/api/Company/GetCompany",
    method: "get",
    params: {
      production_Batch: route.query.production_Batch,
    },
  })
    .then((res) => {
      enterpriseInfo.value = { ...res.data.data[0] };
    })
    .catch((err) => {
      console.error("获取企业信息失败:", err);
      ElMessage.error("获取企业信息失败，请检查网络连接");
    });
};

const convertISOToChineseDate = (isoDate: string): string => {
  const [year, month, day] = isoDate.split("-");
  return `${year}年${parseInt(month)}月${parseInt(day)}日`;
};

// 供应商信息相关方法
interface SupplierInfo {
  deepType: number;
  batch_Number: string;
  production_Batch: string;
}

// 统一的供应商信息对象
const supplierInfo = ref<{ [key: number]: SupplierInfo }>({
  1: {
    deepType: 1,
    batch_Number: "",
    production_Batch: route.query.production_Batch as string,
  }, // 原料
  2: {
    deepType: 2,
    batch_Number: "",
    production_Batch: route.query.production_Batch as string,
  }, // 辅料
  3: {
    deepType: 3,
    batch_Number: "",
    production_Batch: route.query.production_Batch as string,
  }, // 添加剂
  4: {
    deepType: 4,
    batch_Number: "",
    production_Batch: route.query.production_Batch as string,
  }, // 包材
});

// 统一的供应商表单对象
const supplierForm = ref<SupplierInfo>({
  deepType: 0,
  batch_Number: "",
  production_Batch: "",
});

// 验证生产批次不能包含特殊字符
const validateBatchNoSpecialChar = (rule: any, value: any, callback: any) => {
  if (!value && !supplierInfo.value[rule.field]) {
    callback(new Error("请输入生产批次"));
    return;
  }
  if (value) {
    const specialCharRegex =
      /[`~!@#$%^&*()+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——+={}|《》？：""【】、；''，。、]/;
    if (specialCharRegex.test(value)) {
      callback(new Error("生产批次不能包含特殊字符"));
    } else if (value.length > 30) {
      callback(new Error("生产批次长度不能超过30个字符"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};

// 供应商信息校验规则
const supplierRules = {
  batch_Number: [
    { required: true, message: "请输入生产批次", trigger: "blur" },
    { validator: validateBatchNoSpecialChar, trigger: "blur" },
    { max: 30, message: "生产批次长度不能超过30个字符", trigger: "blur" },
  ],
};

// 获取供应商信息的统一方法
const getSupplierInfo = () => {
  return new Promise((resolve, reject) => {
    axios({
      url: "https://localhost:7008/api/Supplier/GetSupplier",
      method: "get",
      params: {
        production_Batch: route.query.production_Batch,
      },
    })
      .then((res) => {
        if (res.data.code === 200) {
          res.data.data.forEach((item: SupplierInfo) => {
            if (item.deepType && item.deepType >= 1 && item.deepType <= 4) {
              supplierInfo.value[item.deepType] = item;
            }
          });
        } else {
          // 初始化供应商信息
          for (let i = 1; i <= 4; i++) {
            supplierInfo.value[i] = {
              deepType: i,
              batch_Number: "",
              production_Batch: route.query.production_Batch as string,
            };
          }
        }
        resolve(res);
      })
      .catch((error) => {
        console.error("获取供应商信息失败:", error);
        ElMessage.error("获取供应商信息失败，请检查网络连接");
        reject(error);
      });
  });
};

// 保存供应商信息的统一方法
const handleSaveSupplierInfo = async (type: number) => {
  // 根据类型获取对应的表单引用
  let formRef;
  switch (type) {
    case 1:
      formRef = supplierRawFormRef.value;
      break;
    case 2:
      formRef = supplierAuxFormRef.value;
      break;
    case 3:
      formRef = supplierAddFormRef.value;
      break;
    case 4:
      formRef = supplierPackFormRef.value;
      break;
  }

  if (!formRef) return;

  await formRef.validate(async (valid: boolean) => {
    if (valid) {
      supplierForm.value.deepType = type;
      supplierForm.value.production_Batch = route.query
        .production_Batch as string;

      try {
        const res = await axios({
          url: "https://localhost:7008/api/Supplier/CreateSupplier",
          method: "post",
          data: supplierForm.value,
        });

        if (res.data.code === 200) {
          ElMessage.success(res.data.msg);
          // 更新本地数据
          supplierInfo.value[type] = { ...supplierForm.value };
          // 关闭对应的对话框
          switch (type) {
            case 1:
              supplierRawDialogVisible.value = false;
              break;
            case 2:
              supplierAuxDialogVisible.value = false;
              break;
            case 3:
              supplierAddDialogVisible.value = false;
              break;
            case 4:
              supplierPackDialogVisible.value = false;
              break;
          }
          // 刷新数据
          getSupplierInfo();
        } else {
          ElMessage.error(res.data.msg);
        }
      } catch (error) {
        ElMessage.error("保存失败，请检查网络连接");
      }
    }
  });
};

// 监听对话框打开，初始化对应类型的表单数据
watch(
  [
    supplierRawDialogVisible,
    supplierAuxDialogVisible,
    supplierAddDialogVisible,
    supplierPackDialogVisible,
  ],
  (newVals) => {
    const [rawVisible, auxVisible, addVisible, packVisible] = newVals;

    if (rawVisible) {
      supplierForm.value = { ...supplierInfo.value[1] };
      if (supplierRawFormRef.value) {
        supplierRawFormRef.value.clearValidate();
      }
    } else if (auxVisible) {
      supplierForm.value = { ...supplierInfo.value[2] };
      if (supplierAuxFormRef.value) {
        supplierAuxFormRef.value.clearValidate();
      }
    } else if (addVisible) {
      supplierForm.value = { ...supplierInfo.value[3] };
      if (supplierAddFormRef.value) {
        supplierAddFormRef.value.clearValidate();
      }
    } else if (packVisible) {
      supplierForm.value = { ...supplierInfo.value[4] };
      if (supplierPackFormRef.value) {
        supplierPackFormRef.value.clearValidate();
      }
    }
  }
);

// ... existing code ...

// 在script setup中添加计算属性
const breedingProgress = computed(() => {
  let total = 5; // 总共5项：养殖信息、免疫信息、动检证、企业信息和企业图片
  let completed = 0;

  // 检查养殖信息
  if (
    breedingInfo.value &&
    breedingInfo.value.breed_Type &&
    breedingInfo.value.breed_Type !== ""
  ) {
    completed++;
  }

  // 检查免疫信息
  if (healthRecords.value && healthRecords.value.length > 0) {
    completed++;
  }

  // 检查动检证
  if (animalCertImages.value && animalCertImages.value.length > 0) {
    completed++;
  }

  // 检查企业信息
  if (
    enterpriseInfo.value &&
    enterpriseInfo.value.livestock_Farm &&
    enterpriseInfo.value.livestock_Farm !== ""
  ) {
    completed++;
  }

  // 检查企业图片
  if (breedingCompanyImages.value && breedingCompanyImages.value.length > 0) {
    completed++;
  }

  return `${completed}/${total}`;
});

const slaughterProgress = computed(() => {
  let total = 4; // 总共4项：屠宰信息、相关资质、企业信息、企业照片
  let completed = 0;

  // 检查屠宰信息
  if (
    slaughterInfo.value &&
    slaughterInfo.value.batch_No &&
    slaughterInfo.value.batch_No !== ""
  ) {
    completed++;
  }

  // 检查相关资质
  if (slaughterImages.value && slaughterImages.value.length > 0) {
    completed++;
  }

  // 检查企业信息
  if (
    enterpriseInfo.value &&
    enterpriseInfo.value.corporate_Name &&
    enterpriseInfo.value.province &&
    enterpriseInfo.value.location_City &&
    enterpriseInfo.value.detailed_Address &&
    enterpriseInfo.value.establishment_Date
  ) {
    completed++;
  }

  // 检查企业照片
  if (slaughterCompanyImages.value && slaughterCompanyImages.value.length > 0) {
    completed++;
  }

  return `${completed}/${total}`;
});

const processingProgress = computed(() => {
  let total = 5; // 总共5项：深加工信息、食品安全信息、供应商信息、企业信息、企业照片
  let completed = 0;

  // 检查深加工信息
  if (
    processingInfo.value &&
    processingInfo.value.work_Team &&
    processingInfo.value.work_Team !== ""
  ) {
    completed++;
  }

  // 检查食品安全信息
  if (safetyImages.value && safetyImages.value.length > 0) {
    completed++;
  }

  // 检查供应商信息
  if (
    supplierInfo.value &&
    Object.values(supplierInfo.value).some(
      (info) => info && info.batch_Number && info.batch_Number !== ""
    )
  ) {
    completed++;
  }

  // 检查企业信息
  if (
    processingInfo.value &&
    processingInfo.value.corporate_Name &&
    processingInfo.value.corporate_Name !== ""
  ) {
    completed++;
  }

  // 检查企业照片
  if (
    processingCompanyImages.value &&
    processingCompanyImages.value.length > 0
  ) {
    completed++;
  }

  return `${completed}/${total}`;
});

// 图片管理相关
interface ImageInfo {
  pictureName: string;
  imgUrl: string;
  pictureType: number;
  production_Batch: string;
}

// 统一的图片列表管理
const imageList = ref<{ [key: number]: ImageInfo[] }>({
  1: [], // 产品检验报告
  2: [], // 动检证
  3: [], // 养殖信息中的企业照片
  4: [], // 屠宰信息的相关资质
  5: [], // 屠宰信息的企业图片
  6: [], // 深加工信息的食品安全信息
  7: [], // 原料相关材料
  8: [], // 辅料相关材料
  9: [], // 添加剂相关材料
  10: [], // 包材相关材料
  11: [], // 深加工企业图片
});

// 获取指定类型的图片列表
const fetchImagesByType = async (type: number) => {
  try {
    const response = await axios.get(
      "https://localhost:7008/api/MinioImg/GetImagesByBatchAndType",
      {
        params: {
          batch: route.query.production_Batch,
          imgType: type,
        },
      }
    );

    if (response.data) {
      imageList.value[type] = Array.isArray(response.data)
        ? response.data.filter((item: any) => item && item.imgUrl)
        : [];
    }
  } catch (error) {
    console.error(`获取类型 ${type} 的图片列表失败:`, error);
  }
};

// 初始化所有类型的图片列表
const initializeAllImages = async () => {
  const types = Object.keys(imageList.value).map(Number);
  await Promise.all(types.map((type) => fetchImagesByType(type)));
};

// 在组件挂载时初始化图片列表
onMounted(async () => {
  await initializeAllImages();
});

const exportDialogVisible = ref(false);
const exportFormRef = ref();
const exportForm = ref({
  exportCount: "",
});
const exportRules = {
  exportCount: [
    { required: true, message: "请输入导出数量", trigger: "blur" },
    { pattern: /^\d{1,4}$/, message: "只能输入1-4位数字", trigger: "blur" },
  ],
};
const handleExportCountInput = (value: string) => {
  exportForm.value.exportCount = value.replace(/\D/g, "").slice(0, 4);
};
const handleExportDialogClose = () => {
  if (exportFormRef.value) {
    exportFormRef.value.resetFields();
  }
};
const executeExport = async (count: number) => {
  try {
    const qrContent = {
      production_Batch: basicInfo.value.batchNumber,
      goodsName: basicInfo.value.productName,
      manufacturer: basicInfo.value.manufacturer,
      licenseNumber: basicInfo.value.licenseNumber,
      shelfLife: basicInfo.value.shelfLife,
      printCount: count,
    };
    const qrString = JSON.stringify(qrContent);
    const qrDataUrl = await QRCode.toDataURL(qrString, {
      width: 300,
      margin: 2,
      color: {
        dark: "#000000",
        light: "#ffffff",
      },
    });
    const link = document.createElement("a");
    link.download = `溯源码_${basicInfo.value.batchNumber}_${count}张.png`;
    link.href = qrDataUrl;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success(`成功导出${count}张溯源码`);
    exportDialogVisible.value = false;
  } catch (error) {
    console.error("生成二维码失败:", error);
    ElMessage.error("溯源码导出失败，请重试");
  }
};
const confirmExport = async () => {
  if (!exportFormRef.value) return;
  await exportFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const count = parseInt(exportForm.value.exportCount);
      await executeExport(count);
    }
  });
};
</script>

<style scoped>
.batch-detail {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.tab-header {
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
  padding: 0 20px;
  height: 40px;
  display: flex;
  align-items: center;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 16px;
  height: 100%;
  font-size: 14px;
  color: #303133;
  border-bottom: 2px solid #409eff;
}

.close-icon {
  cursor: pointer;
  font-size: 16px;
  color: #909399;
  transition: all 0.3s;
}

.close-icon:hover {
  color: #303133;
}

.product-info {
  display: flex;
  gap: 24px;
  background: #fff;
  padding: 24px;
  margin-bottom: 20px;
}

.product-image {
  width: 200px;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
}

.product-image .el-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.info-row {
  display: flex;
  gap: 48px;
  margin-bottom: 16px;
}

.report-section {
  margin-top: 24px;
}

.report-section h3 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
}

.section-card {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.nav-buttons {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 0 20px;
}

.nav-button {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 8px 0;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #606266;
  position: relative;
}

.button-text {
  font-size: 14px;
}

.progress-tag {
  font-size: 12px;
  color: #1890ff;
}

.nav-button:hover {
  color: #1890ff;
}

.nav-button.active {
  color: #1890ff;
}

.nav-button.active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #1890ff;
}

.section-content {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

.info-section,
.health-section {
  margin-bottom: 24px;
  background: #fff;
  border-radius: 4px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 16px;
}

.section-title .title {
  font-size: 14px;
  color: #1890ff;
  font-weight: 500;
}

.setting-btn,
.add-btn {
  display: flex;
  align-items: center;
  gap: 8px;
}

.badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  background: #909399;
  color: #fff;
  border-radius: 50%;
  font-size: 12px;
}

.info-row {
  display: flex;
  gap: 24px;
  margin-bottom: 16px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-item {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: #fff;
}

.info-item .label {
  color: #909399;
  min-width: 100px;
}

.health-table {
  margin-top: 16px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.table-footer {
  margin-top: 16px;
  display: flex;
  justify-content: center;
  gap: 16px;
}

.footer-buttons {
  display: flex;
  gap: 12px;
}

.page-info {
  display: flex;
  gap: 8px;
}

.section-block {
  margin-top: 24px;
}

.block-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.document-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 16px;
}

.document-card {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.document-card .el-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.document-label {
  padding: 8px;
  text-align: center;
  background: #fff;
  border-top: 1px solid #e4e7ed;
}

.upload-card {
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.upload-card:hover {
  border-color: #1890ff;
}

.supply-chain-section {
  margin-top: 24px;
}

.supplier-category {
  margin-bottom: 24px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.category-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.category-info {
  margin-bottom: 16px;
}

.el-table {
  margin-top: 16px;
}

.enterprise-section {
  margin-top: 24px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.setting-btn {
  padding: 0;
  height: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.address-row {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  width: 100%;
}

.address-row :deep(.region-select) {
  flex: 0 0 auto;
}

.address-row .detailed-address {
  flex: 1;
}

.button-group {
  display: flex;
  gap: 16px;
  align-items: center;
}

.enterprise-info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  padding: 16px 0;
}

.enterprise-info-grid .info-item {
  margin: 0;
  padding: 12px 16px;
}

.enterprise-info-grid .info-item:last-child {
  grid-column: 1 / -1;
}

.address-inputs {
  display: flex;
  gap: 8px;
  width: 100%;
}

.address-inputs .address-select {
  width: 120px;
}

.address-inputs .address-input {
  flex: 1;
}

/* 图片上传组件容器样式 */
.standard-uploader {
  margin: 16px 0;
  padding: 0;
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  gap: 12px;
}

.operation-buttons .el-button {
  font-size: 14px;
  padding: 8px 16px;
}

.product-name {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}
</style>
